package com.zhu.esyblog.Handler;

import com.alibaba.fastjson.JSON;
import com.zhu.esyblog.Utils.UserThreadLocal;
import com.zhu.esyblog.pojo.RespBean;
import com.zhu.esyblog.pojo.SysUser;
import com.zhu.esyblog.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component //让spring识别这个拦截器
public class LoginHandler implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;
    /**
     * 再执行方法之前进行执行 可以做拦截登录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1.需要判断 请求接口的路径是否是controller方法 是拦截
         * 2.判断token是否为空 为空 未登录
         * 3.token 不为空 登陆验证  checkToken()
         * 4.认证成功，放行
         *
         */
        if(!(handler instanceof HandlerMethod)){  //如果不是controller的方法放行
            return true;
        }
        //1.获得token
        String token = request.getHeader("Authorization");
        //token为空 失败
        if(StringUtils.isEmpty(token)){
            RespBean error = RespBean.error("未登录!", 10001);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(error));
            return false;
        }
        //检查token信息 如果信息里面的user是空的 则可能是伪造的token 失败
        SysUser user = loginService.checkToken(token);
        if(user==null){
            RespBean error = RespBean.error("未登录!", 10001);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(error));
            return false;
        }
        UserThreadLocal.put(user);
        return true;
    }

    /**
     * 结束之后做的事
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除ThreadLocal中的信息
        UserThreadLocal.remove();
    }
}
